package com.jiaoyou.baojian.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.KeyguardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.os.PowerManager;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;

import com.alibaba.sdk.android.ams.common.util.Md5Util;
import com.bumptech.glide.Glide;
import com.github.florent37.viewanimator.AnimationListener;
import com.github.florent37.viewanimator.ViewAnimator;
import com.google.gson.Gson;
import com.jiaoyou.baojian.BaojianApplication;
import com.jiaoyou.baojian.R;
import com.jiaoyou.baojian.activity.TalkingActivity;
import com.jiaoyou.baojian.constvalue.ConstValue;
import com.jiaoyou.baojian.entity.GiftEntity;
import com.jiaoyou.baojian.entity.UserEntity;
import com.jiaoyou.baojian.entity.response.LoginResponse;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;

import static android.content.Context.ACTIVITY_SERVICE;
import static android.content.Context.POWER_SERVICE;

/**
 * Created by DemonZYM on 17/5/1.
 */

public class Utils {
    public static boolean isLogin(){
        ACache aCache = ACache.get(BaojianApplication.getInstance());
        if(!TextUtils.isEmpty(aCache.getAsString("mobile_token"))){
            Gson gson = new Gson();
            if(!TextUtils.isEmpty(aCache.getAsString(LoginResponse.TAG))) {
                try {
                    LoginResponse response = gson.fromJson(aCache.getAsString(LoginResponse.TAG), LoginResponse.class);
                    if (response != null && response.user != null && response.userInfo != null)
                        return true;
                } catch (Exception e) {
                }
            }
        }
        aCache.put("mobile_token", "");
        aCache.put(LoginResponse.TAG, "");
        return false;
    }

    public static void ignoreBatteryOptimization(Activity activity) {
        Context context = BaojianApplication.getInstance();
        PowerManager powerManager = (PowerManager) context.getSystemService(POWER_SERVICE);
        boolean hasIgnored = true;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            hasIgnored = powerManager.isIgnoringBatteryOptimizations(context.getPackageName());
        }
        //  判断当前APP是否有加入电池优化的白名单，如果没有，弹出加入电池优化的白名单的设置对话框。
        if(!hasIgnored) {
            Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + context.getPackageName()));
            activity.startActivity(intent);
        }
    }

    public static void wakeUpAndUnlock(Context context){
        KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
        KeyguardManager.KeyguardLock kl = km.newKeyguardLock("unLock");
        //解锁
        kl.disableKeyguard();
        //获取电源管理器对象
        PowerManager pm = (PowerManager) context.getSystemService(POWER_SERVICE);
        //获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK,"bright");
        //点亮屏幕
        wl.acquire();
        //释放
        wl.release();
    }

//    public static String getP2PChannelName(int userId, int zhuboId){
//        return md5(userId + "_" + zhuboId);
//    }

    public static String md5(String str){
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(str.getBytes());
            // digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            return new BigInteger(1, md.digest()).toString(16);
        } catch (Exception e) {
        }
        return "";
    }

    public static String randomString8(){
        return randomString(8);
    }
    public static String randomString(int length){
        String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public static void toolgleKeyboard(Context context){
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public static void showKeyboard(View view, Context context){
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
    }

    public static void hideKeyboard(View view, Context context){
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏
    }

    public static String generalChannelName(int userId){
        return "baofang_" + userId;
    }

    public static File generalTempFile(String suffix){
        File file = new File(Environment.getExternalStorageDirectory(),
                "/temp/" + randomString8() + suffix);
        if (!file.getParentFile().exists())
            file.getParentFile().mkdirs();
        return file;
    }

    //返回值 -1：没有网络  1：WIFI网络2：wap网络3：net网络
    public static String getNetType()
    {
        ConnectivityManager connMgr = (ConnectivityManager) BaojianApplication.getInstance()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if(networkInfo == null)
        {
            return "no_network";
        }
        int type = networkInfo.getType();
        if(type == ConnectivityManager.TYPE_MOBILE)
        {
            if(networkInfo.getExtraInfo() == null)
                return "unknown";
            else
                return networkInfo.getExtraInfo().toLowerCase();
        }
        else if(type == ConnectivityManager.TYPE_WIFI)
        {
            return "wifi";
        }
        return "no_network";
    }

    public static String exchangeZhuboTypeString(String type){
        switch (type){
            case "SHAO_FU":
                type = "少妇";
                break;
            case "REN_QI":
                type = "人妻";
                break;
            case "SHU_NV":
                type = "熟女";
                break;
            case "YU_JIE":
                type = "御姐";
                break;
            case "LUO_LI":
                type = "萝莉";
                break;
            case "OL":
                type = "OL";
                break;
        }
        return type;
    }

    public static String exchangeZhuboType(String type){
        switch (type){
            case "少妇":
                type = "SHAO_FU";
                break;
            case "人妻":
                type = "REN_QI";
                break;
            case "熟女":
                type = "SHU_NV";
                break;
            case "御姐":
                type = "YU_JIE";
                break;
            case "萝莉":
                type = "LUO_LI";
                break;
            case "OL":
                type = "OL";
                break;
            case "全部":
                type = "";
                break;
        }
        return type;
    }

    public static String getImageUrl(Context context, String path){
        return ACache.get(BaojianApplication.getInstance()).getAsString("imageDomain") + path;
    }

    public static void showImage(Context context, String path, ImageView imageView){
        if(TextUtils.isEmpty(path))
            return;
        Glide.with(context).load(getImageUrl(context, path))
//                .placeholder(R.drawable.icon_placeholder)
//                .crossFade()
                .into(imageView);
    }

    public static void showImageNoFade(Context context, String path, ImageView imageView){
        if(TextUtils.isEmpty(path))
            return;
        Glide.with(context).load(getImageUrl(context, path)).into(imageView);
    }

    public static void showCircleImage(Context context, String path, ImageView imageView){
        Glide.with(context)
                .load(getImageUrl(context, path))
//                .placeholder(R.drawable.icon_placeholder)
//                .crossFade()
                .transform(new GlideCircleTransform(context))
                .into(imageView);
    }

    public static void showGiftImage(Context context, String path, ImageView imageView){
        Glide.with(context).load(getImageUrl(context, path))
//                .crossFade()
//                .placeholder(R.drawable.icon_placeholder)
                .into(imageView);
    }

    public static int getShengyouTypeImage(String type){
        if(TextUtils.isEmpty(type))
            return R.drawable.icon_woman;
        switch (type){
            case "SHAO_FU":
                return R.drawable.icon_woman;
            case "REN_QI":
                return R.drawable.icon_wife;
            case "SHU_NV":
                return R.drawable.icon_mature;
            case "YU_JIE":
                return R.drawable.icon_sister;
            case "LUO_LI":
                return R.drawable.icon_girl;
            case "OL":
                return R.drawable.icon_ol;
        }
        return 0;
    }

    public static void showShengyouTypeImage(Context context, String type, ImageView imageView){
        if(TextUtils.isEmpty(type)){
            imageView.setVisibility(View.GONE);
            return;
        }
        imageView.setVisibility(View.VISIBLE);
        switch (type){
            case "SHAO_FU":
                Glide.with(context).load(R.drawable.icon_woman)
//                        .placeholder(R.drawable.icon_placeholder)
//                        .crossFade()
                        .into(imageView);
                break;
            case "REN_QI":
                Glide.with(context).load(R.drawable.icon_wife)
//                        .placeholder(R.drawable.icon_placeholder)
//                        .crossFade()
                        .into(imageView);
                break;
            case "SHU_NV":
                Glide.with(context).load(R.drawable.icon_mature)
//                        .placeholder(R.drawable.icon_placeholder)
//                        .crossFade()
                        .into(imageView);
                break;
            case "YU_JIE":
                Glide.with(context).load(R.drawable.icon_sister)
//                        .placeholder(R.drawable.icon_placeholder)
//                        .crossFade()
                        .into(imageView);
                break;
            case "LUO_LI":
                Glide.with(context).load(R.drawable.icon_girl)
//                        .placeholder(R.drawable.icon_placeholder)
//                        .crossFade()
                        .into(imageView);
                break;
            case "OL":
                Glide.with(context).load(R.drawable.icon_ol)
//                        .placeholder(R.drawable.icon_placeholder)
//                        .crossFade()
                        .into(imageView);
                break;
        }
    }

    public static int getAge(String birthday){
        if(TextUtils.isEmpty(birthday))
            return 18;
        int nowYear = new Date().getYear();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = sdf.parse(birthday);
        } catch (ParseException e) {
            e.printStackTrace();
            return 18;
        }
        int birthYear = date.getYear();
        return nowYear - birthYear;
    }

    public static String getRankRange(String title){
        switch (title){
            case "日榜":
                title = "DAILY";
                break;
            case "周榜":
                title = "WEEKLY";
                break;
            case "月榜":
                title = "MONTHLY";
                break;
            case "总榜":
                title = "TOTAL";
                break;
        }
        return title;
    }

    public static void doHttpGet(String baseUrl, HashMap<String, String> paramsMap, Callback cb){
        StringBuilder tempParams = new StringBuilder();
        int pos = 0;
        for (String key : paramsMap.keySet()) {
            if (pos > 0) {
                tempParams.append("&");
            }
            //对参数进行URLEncoder
            try {
                tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get(key), "utf-8")));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            pos++;
        }
        String requestUrl = String.format("%s?%s", baseUrl, tempParams.toString());
        OkHttpClient client = new OkHttpClient();
        Request.Builder builder = new Request.Builder()
                .url(requestUrl);
        Request request = builder.build();
        client.newCall(request).enqueue(cb);
    }

    public static String getIPAddress() {
        Context context = BaojianApplication.getInstance();
        NetworkInfo info = ((ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
                try {
                    //Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                }

            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
                return ipAddress;
            }
        } else {
            //当前无网络连接,请在设置中打开网络
        }
        return null;
    }

    /**
     * 将得到的int类型的IP转换为String类型
     *
     * @param ip
     * @return
     */
    public static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }

    public static void showGiftAnimation(Activity activity, int giftid, List<GiftEntity> giftList) {
        final ViewGroup root = (ViewGroup) activity.getWindow().getDecorView();
        String giftImage = getGiftUrlFromGiftList(giftid, giftList);
//        String giftImage = "public/gift/candy.png";
        final ImageView imageView = new ImageView(activity);
        WindowManager wm = activity.getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        int imageW = dp2pix(activity, 45);
        int imageX = (width - imageW) / 2;
        int imageY = (height - imageW) / 2;
        ViewGroup.LayoutParams layoutParams =
                new ViewGroup.LayoutParams(imageW,
                        imageW);
        imageView.setX(imageX);
        imageView.setY(imageY);
        imageView.setLayoutParams(layoutParams);
        root.addView(imageView);
        showImageNoFade(activity, giftImage, imageView);
        ViewAnimator.animate(imageView)
                .scale(0.2f, 1.3f, 0.8f, 1.2f, 0.9f, 1f)
                .alpha(0.6f, 1f)
                .dp()
                .duration(1500)
                .thenAnimate(imageView)
                .rotation(1440)
                .scale(1f, 0.2f)
                .alpha(1f, 0.2f)
                .dp()
                .translationX(10)
                .translationY(30)
                .accelerate()
                .duration(1000)
                .onStop(new AnimationListener.Stop() {
                    @Override
                    public void onStop() {
                        root.removeView(imageView);
                    }
                })
                .start();
    }

    public static String getGiftUrlFromGiftList(int giftid, List<GiftEntity> giftList) {
        for(GiftEntity giftEntity : giftList){
            if(giftEntity.getId() == giftid)
                return giftEntity.getImg();
        }
        return "";
    }

    public static String getGiftNameFromGiftList(int id, List<GiftEntity> giftList){
        for(GiftEntity giftEntity : giftList){
            if(giftEntity.getId() == id)
                return giftEntity.getDescription();
        }
        return "";
    }

    /**
     * 将dp转换为px像素
     * @param context
     * @param dp
     * @return
     */
    public static int dp2pix(Activity context, float dp){
        float density = context.getResources().getDisplayMetrics().density;
        return (int)(density * dp + 0.5f);

    }

    /**
     * 将px转换为dp
     * @param context
     * @param pix
     * @return
     */
    public static int pix2dp(Activity context, float pix){
        float density = context.getResources().getDisplayMetrics().density;
        return (int)(pix / density + 0.5f);
    }

    /**
     * 程序是否在前台运行
     *
     * @return
     */
    public static boolean isRunningForeground() {
        Context context = BaojianApplication.getInstance();
        ActivityManager activityManager = (ActivityManager) context.getApplicationContext()
                .getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = context.getApplicationContext().getPackageName();
        /**
         * 获取Android设备中所有正在运行的App
         */
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }

        return false;
    }

    /**
     * 获取渠道名
     * @return 如果没有获取成功，那么返回值为空
     */
    public static String getChannelName() {
        Context ctx = BaojianApplication.getInstance();
        String channelName = null;
        try {
            PackageManager packageManager = ctx.getPackageManager();
            if (packageManager != null) {
                //注意此处为ApplicationInfo 而不是 ActivityInfo,因为友盟设置的meta-data是在application标签中，而不是某activity标签中，所以用ApplicationInfo
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(ctx.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        //此处这样写的目的是为了在debug模式下也能获取到渠道号，如果用getString的话只能在Release下获取到。
                        channelName = applicationInfo.metaData.get("UMENG_CHANNEL") + "";
                    }
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return channelName;
    }

    /**
     * 获取application中指定的meta-data
     * @return 如果没有获取成功(没有对应值，或者异常)，则返回值为空
     */
    public static String getAppMetaData(Context ctx, String key) {
        if (ctx == null || TextUtils.isEmpty(key)) {
            return null;
        }
        String resultData = null;
        try {
            PackageManager packageManager = ctx.getPackageManager();
            if (packageManager != null) {
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(ctx.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        resultData = applicationInfo.metaData.getString(key);
                    }
                }

            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return resultData;
    }

//    public static String getAgoraToken(String account){
//        String appId             = ConstValue.AGORA_APPID; //App ID
//        String appCertificate    = ConstValue.AGORA_CERTIFICATE; //App Certificate
//        String expiredTime       = (System.currentTimeMillis() / 1000) + "3600"; // 授权时间戳
//        return "1:" + appId + ":" + expiredTime + ":" + Utils.md5(account + appId + appCertificate + expiredTime);
//    }

    public static boolean isMainProcess() {
        ActivityManager am = (ActivityManager) BaojianApplication.getInstance().getSystemService(ACTIVITY_SERVICE);//app运行状态管理权限
        int pid = android.os.Process.myPid();//当前运行时的进程id
        Log.d("isMainProcess","pid="+pid);
        String packageName = BaojianApplication.getInstance().getPackageName();
        for (ActivityManager.RunningAppProcessInfo info : am.getRunningAppProcesses()) {
            Log.d("isMainProcess","info.pid="+info.pid);
            if (info.pid == pid && packageName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    public static String getAgoraToken(String account){
        String appId             = ConstValue.AGORA_APPID; //App ID
        String appCertificate    = ConstValue.AGORA_CERTIFICATE; //App Certificate
        String expiredTime       = (System.currentTimeMillis() / 1000) + "3600"; // 授权时间戳
        return "1:" + appId + ":" + expiredTime + ":" + Utils.md5(account + appId + appCertificate + expiredTime);
    }
}
